/*
 * @Descripttion:
 * @Author: Wang Dejiang(aei)
 * @Date: 2022-04-12 21:23:00
 * @LastEditors: Wang Dejiang(aei)
 * @LastEditTime: 2022-04-29 00:29:26
 */
import { el } from 'element-plus/lib/locale'
import { nextTick, onMounted } from 'vue'
import {
  NavigationGuardWithThis,
  NavigationHookAfter,
  Router,
  RouteRecordName,
} from 'vue-router'
import { useStore } from '../pinia/store'

export const useBeaforeEach: NavigationGuardWithThis<undefined> = (
  to,
  from,
  next
) => {
  // console.log('跳转', to)
  //动态更换html的title
  window.document.title =
    to.meta.title == undefined ? 'zx中文文档' : (to.meta.title as string)
  next()
}

export const useAfterEach: NavigationHookAfter = async (to, from, next) => {
  const store = useStore()
  //根据router的name来确定TopMenu组件的menuIndex
  interface RouteRecordNameArr {
    [PropName: RouteRecordName]: string
  }
  const arr: RouteRecordNameArr = {
    Home: 'home',
    Guide: 'guide',
    Apis: 'apis',
    About: 'about',
  }
  if (to.name && arr[to.name]) store.setPageIndex(arr[to.name])

  //如果有锚点，跳转到相应位置
  if (to.hash) {
    //等待dom更新后在进行，避免可能虚拟DOM没有渲染完成
    setTimeout(() => {
      //更改全局的apiIndex,并且定位响应位置
      if (to.name === 'Apis' && to.hash) {
        store.setApiIndex(to.hash.substring(1))
        document.querySelector(to.hash)?.scrollIntoView({
          behavior: 'smooth',
          block: 'center',
        })
      }
      document.querySelector(to.hash + '_title')?.scrollIntoView({
        block: 'center',
        behavior: 'smooth',
      })
    })
  }
}
